# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
    QStyledItemDelegate,
    QSizePolicy,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage, QIcon
import sys
import csv
import os
import json
import subprocess
import re
from ..util.parameter_mapping import (
    mainConnectMap,
    rodConnectMap,
    mainConnectReverseMap,
    rodConnectReverseMap,
    typeBundleMap,
    typeBundleReverseMap,
)
from gui.controls import envs
from .. import config as Config
from ..utils import Utils
from .. import message_box as MBox
from ..dlg_model_params import DlgModeResetCls
from ..params_table import ParamsTable, OnlyOneRowTable
from ..custom_widget import SelectBox, LineEditInt, SelectSearchBox, LineEditStr
from ..bundle_connection.add_connection import DlgAddConnection
from ..util.utils_empty import var_is_empty


singleHeight = 60


class CustomTabWidget(QTabWidget):
    add_tab_signal = Signal()

    def __init__(self, parent=None):
        super(CustomTabWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        # 设置标签位置
        self.setTabPosition(QTabWidget.North)

        # 创建右侧按钮
        addBtn = QPushButton()
        self.set_button_image(addBtn, "icons/plugins/qmodeling/add.png")
        addBtn.clicked.connect(self.add_tab_signal.emit)
        # lab.setFixedSize(30, 20)

        # 将按钮添加到标签栏
        self.tabBar().setLayoutDirection(Qt.LeftToRight)

        self.setCornerWidget(addBtn, Qt.TopRightCorner)

    def set_button_image(self, button, image_path):
        """设置按钮的图片，并保持等比宽高，同时设置边距"""
        pixmap = QPixmap(image_path)
        if pixmap.isNull():
            print("Error: Unable to load image.")
            return

        # 等比缩放图片到指定大小（15x15像素）
        scaled_pixmap = pixmap.scaled(
            15, 15, Qt.KeepAspectRatio, Qt.SmoothTransformation
        )

        # 将 QPixmap 转换为 QIcon
        icon = QIcon(scaled_pixmap)

        # 设置按钮图标和大小
        button.setIcon(icon)  # 使用 QIcon 设置图标
        button.setIconSize(scaled_pixmap.size())  # 设置图标大小
        button.setStyleSheet(
            """
                             QPushButton { 
                                margin-right:3px;
                                min-width: 25px !important; 
                                max-width: 25px !important; 
                                min-height: 15px !important; 
                                max-height: 15px !important;
                                border-bottom-left-radius: 0px;
                                border-bottom-right-radius: 0px; 
                             }"""
        )


class DlgBundleConnection(DlgModeResetCls):
    materialLibraryLocking_update_signal = Signal(object)
    bundleConnection_save_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("捆绑连接")
        self.resize(750, 700)

        self.tabWidgetList = []
        self.otherWidgetList = []
        self.connects = params.get("connects") or {}
        self.info = self.parseContects(self.connects)
        self.materialOptions = self.getMaterialOption()

        self.cacheFile1 = Config.cachePath + "bundleConnection123.json"
        Utils.write_json(self.cacheFile1, params)
        self.cacheFile1 = Config.cachePath + "bundleConnection123456.json"
        Utils.write_json(self.cacheFile1, self.info)

        self.isLoading = False

        layout = QVBoxLayout()

        self.tabs = CustomTabWidget()
        self.tabs.tabBarDoubleClicked.connect(self.on_tab_double_clicked)
        self.tabs.add_tab_signal.connect(self.addTab)
        self.mainPage = QWidget()
        self.rodPage = QWidget()

        # 设置选项卡可关闭
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.on_tab_close_requested)

        layout.addWidget(self.tabs)

        btnLayout = QHBoxLayout()
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        self.on_tab_count_changed()

        data = params.get("data") or []

        for i, connection in enumerate(data):
            name = connection.get("name")
            type = connection.get("connectionType")
            self.createTabPage(name, type, i)

        self.updateUI(data)

        # envs.ipimas_changeMaterial = (
        #     lambda library, *args, **kwargs: self.libraryChange(
        #         library, *args, **kwargs
        #     )
        # )

    def on_tab_count_changed(self):
        if self.tabs.count() == 0:
            self.tabs.setStyleSheet(
                """
                            QTabWidget::pane:top {
                            top: 20px;
                             }"""
            )
        else:
            self.tabs.setStyleSheet(
                """
                            QTabWidget::pane:top {
                            top: 0px;
                             }"""
            )

    def on_tab_close_requested(self, index):
        isDel = MBox.confirm("是否确认删除该连接?")
        if isDel:
            self.tabs.removeTab(index)
            self.tabWidgetList.pop(index)
            self.otherWidgetList.pop(index)
            self.on_tab_count_changed()

    def createTabPage(self, name, type, index):
        self.tabWidgetList.append({})
        widgetDict = self.tabWidgetList[-1]
        self.otherWidgetList.append({})
        otherWidgetDict = self.otherWidgetList[-1]

        layout = QVBoxLayout()
        pageWidget = QWidget()
        pageWidget.setLayout(layout)
        self.tabs.addTab(pageWidget, name)

        connectionTopLayout = QHBoxLayout()
        layout.addLayout(connectionTopLayout)

        connectionIdWidget = QWidget()
        connectionIdWidget.setFixedWidth(240)
        connectionIdLayout = QGridLayout()
        freedomLab = QLabel("连接的自由度")
        widgetDict["con_degree"] = LineEditInt()
        widgetDict["con_degree"].setClearButtonEnabled(False)
        if type == "main":
            widgetDict["con_degree"].setValue(123)
        else:
            widgetDict["con_degree"].setValue(123456)
        connectionIdLayout.addWidget(freedomLab, 0, 0)
        connectionIdLayout.addWidget(widgetDict["con_degree"], 0, 1)

        idLab = QLabel("id")
        widgetDict["id"] = LineEditInt()
        widgetDict["id"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(idLab, 1, 0)
        connectionIdLayout.addWidget(widgetDict["id"], 1, 1)
        connectionIdWidget.setLayout(connectionIdLayout)

        widgetDict["connectionType"] = LineEditStr()
        widgetDict["connectionType"].setVisible(False)
        widgetDict["connectionType"].setValue(type)
        widgetDict["connectionType"].setReadOnly(True)
        widgetDict["connectionType"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(widgetDict["connectionType"], 2, 1)
        connectionIdWidget.setLayout(connectionIdLayout)

        connectionTopLayout.addWidget(connectionIdWidget)
        connectionTopLayout.addStretch(1)

        # stage
        gridLayout = QGridLayout()
        stageGroupBox1 = QGroupBox(self.connects.get("connectsTitles")[0].get("title"))
        stageLayout1 = QVBoxLayout()
        stageGroupBox1.setLayout(stageLayout1)
        widgetDict["stageType1"] = SelectBox(
            options=[
                {"title": "点", "value": "点"},
                {"title": "蒙皮桁条", "value": "蒙皮桁条"},
            ],
            index=index,
            onChanged=lambda *args, **kwargs: self.stageType1Changed(*args, **kwargs),
        )

        widgetDict["con_id1"] = SelectSearchBox(options=[])
        widgetDict["stageType1"].setMinimumWidth(100)
        widgetDict["con_id1"].setMinimumWidth(100)
        widgetDict["stageType1"].setMaximumWidth(150)
        widgetDict["con_id1"].setMaximumWidth(150)
        stageLayout1.addWidget(widgetDict["stageType1"])
        stageLayout1.addWidget(widgetDict["con_id1"])

        coordinates1GroupBox = QGroupBox("支座点坐标")
        coordinates1Layout = QVBoxLayout()
        if type == "main":
            widgetDict["coordinates1Table"] = OnlyOneRowTable(rows=0, columns=3)
            widgetDict["coordinates1Table"].setFixedHeight(singleHeight)
            widgetDict["coordinates1Table"].setHorizontalHeaderLabels(
                [
                    "id",
                    "轴向坐标",
                    "径向坐标",
                ]
            )
            widgetDict["coordinates1Table"].rowSetInt([0])
            widgetDict["coordinates1Table"].rowSetFloat([1, 2])
            widgetDict["coordinates1Table"].addRow()
        else:
            widgetDict["coordinates1Table"] = OnlyOneRowTable(rows=0, columns=4)
            widgetDict["coordinates1Table"].setFixedHeight(singleHeight)
            widgetDict["coordinates1Table"].setHorizontalHeaderLabels(
                [
                    "id",
                    "轴向坐标",
                    "径向坐标",
                    "角度",
                ]
            )
            widgetDict["coordinates1Table"].rowSetInt([0])
            widgetDict["coordinates1Table"].rowSetFloat([1, 2, 3])
            widgetDict["coordinates1Table"].addRow()
        coordinates1Layout.addWidget(widgetDict["coordinates1Table"])
        coordinates1GroupBox.setLayout(coordinates1Layout)
        stageLayout1.addWidget(coordinates1GroupBox)

        otherWidgetDict["scope1GroupBox"] = QGroupBox("支座范围")
        otherWidgetDict["scope1GroupBox"].setVisible(False)
        scope1Layout = QVBoxLayout()
        if type == "main":
            widgetDict["scope1Table"] = OnlyOneRowTable(rows=0, columns=3)
            widgetDict["scope1Table"].setFixedHeight(singleHeight)
            widgetDict["scope1Table"].setHorizontalHeaderLabels(
                [
                    "轴向起",
                    "径向止",
                    "周向角度",
                ]
            )
            widgetDict["scope1Table"].rowSetFloat([0, 1, 2])
            widgetDict["scope1Table"].addRow()
        else:
            widgetDict["scope1Table"] = ParamsTable(rows=0, columns=1)
            widgetDict["scope1Table"].setHorizontalHeaderLabels(
                [
                    "角度",
                ]
            )
            widgetDict["scope1Table"].rowSetFloat([0])
        widgetDict["scope1Table"].useFlag = False
        scope1Layout.addWidget(widgetDict["scope1Table"])
        otherWidgetDict["scope1GroupBox"].setLayout(scope1Layout)
        stageLayout1.addWidget(otherWidgetDict["scope1GroupBox"])

        stageGroupBox2 = QGroupBox(self.connects.get("connectsTitles")[1].get("title"))
        section2Layout = QVBoxLayout()
        stageGroupBox2.setLayout(section2Layout)
        widgetDict["stageType2"] = SelectBox(
            options=[],
            index=index,
            onChanged=lambda *args, **kwargs: self.stageType2Changed(*args, **kwargs),
        )
        widgetDict["con_id2"] = SelectSearchBox(options=[])
        widgetDict["stageType2"].setMinimumWidth(100)
        widgetDict["con_id2"].setMinimumWidth(100)
        widgetDict["stageType2"].setMaximumWidth(150)
        widgetDict["con_id2"].setMaximumWidth(150)
        section2Layout.addWidget(widgetDict["stageType2"])
        section2Layout.addWidget(widgetDict["con_id2"])

        coordinates2GroupBox = QGroupBox("支座点坐标")
        coordinates2Layout = QVBoxLayout()
        if type == "main":
            widgetDict["coordinates2Table"] = OnlyOneRowTable(rows=0, columns=3)
            widgetDict["coordinates2Table"].setFixedHeight(singleHeight)
            widgetDict["coordinates2Table"].setHorizontalHeaderLabels(
                [
                    "id",
                    "轴向坐标",
                    "径向坐标",
                ]
            )
            widgetDict["coordinates2Table"].rowSetInt([0])
            widgetDict["coordinates2Table"].rowSetFloat([1, 2])
            widgetDict["coordinates2Table"].addRow()
        else:
            widgetDict["coordinates2Table"] = OnlyOneRowTable(rows=0, columns=5)
            widgetDict["coordinates2Table"].setFixedHeight(singleHeight)
            widgetDict["coordinates2Table"].setHorizontalHeaderLabels(
                [
                    "id",
                    "轴向坐标",
                    "径向坐标",
                    "角度1",
                    "角度2",
                ]
            )
            widgetDict["coordinates2Table"].rowSetInt([0])
            widgetDict["coordinates2Table"].rowSetFloat([1, 2, 3, 4])
            widgetDict["coordinates2Table"].addRow()
        coordinates2Layout.addWidget(widgetDict["coordinates2Table"])
        coordinates2GroupBox.setLayout(coordinates2Layout)
        section2Layout.addWidget(coordinates2GroupBox)

        otherWidgetDict["scope2GroupBox"] = QGroupBox("支座范围")
        otherWidgetDict["scope2GroupBox"].setVisible(False)
        scope2Layout = QVBoxLayout()
        if type == "main":
            widgetDict["scope2Table"] = OnlyOneRowTable(rows=0, columns=3)
            widgetDict["scope2Table"].setFixedHeight(singleHeight)
            widgetDict["scope2Table"].setHorizontalHeaderLabels(
                [
                    "轴向起",
                    "径向止",
                    "周向角度",
                ]
            )
            widgetDict["scope2Table"].rowSetFloat([0, 1, 2])
            widgetDict["scope2Table"].addRow()
        else:
            widgetDict["scope2Table"] = ParamsTable(rows=0, columns=1)
            widgetDict["scope2Table"].setHorizontalHeaderLabels(
                [
                    "角度",
                ]
            )
            widgetDict["scope2Table"].rowSetFloat([0])
        widgetDict["scope2Table"].useFlag = False
        scope2Layout.addWidget(widgetDict["scope2Table"])
        otherWidgetDict["scope2GroupBox"].setLayout(scope2Layout)
        section2Layout.addWidget(otherWidgetDict["scope2GroupBox"])

        icon = envs.qicons.qicon_add()
        addImg = QLabel()
        addImg.setAlignment(Qt.AlignCenter)
        pixmap = icon.pixmap(20, 20)
        addImg.setPixmap(pixmap)

        gridLayout.addWidget(stageGroupBox1, 0, 0)
        gridLayout.addWidget(addImg, 0, 1)
        gridLayout.addWidget(stageGroupBox2, 0, 2)

        sectionLayout = QHBoxLayout()
        sectionLayout.addLayout(gridLayout)
        layout.addLayout(sectionLayout)
        if type == "main":
            mainGroupBox = QGroupBox("主捆绑")
            mainLayout = QVBoxLayout()

            pointGroupBox = QGroupBox("捆绑点")
            pointLayout = QVBoxLayout()
            widgetDict["pointTable"] = OnlyOneRowTable(rows=0, columns=4)
            widgetDict["pointTable"].setHorizontalHeaderLabels(
                [
                    "id",
                    "轴向坐标",
                    "径向坐标",
                    "连接自由度",
                ]
            )
            widgetDict["pointTable"].cellChanged.connect(self.on_pointTable_changed)
            widgetDict["pointTable"].rowSetFloat([1, 2])
            widgetDict["pointTable"].rowSetInt([0, 3])
            widgetDict["pointTable"].addRow()
            widgetDict["pointTable"].addRow()
            pointLayout.addWidget(widgetDict["pointTable"])
            widgetDict["pointTable"].adjust_table_height(2)
            pointGroupBox.setLayout(pointLayout)

            boltGroupBox = QGroupBox("捆绑螺栓")
            boltLayout = QVBoxLayout()
            widgetDict["boltTable"] = OnlyOneRowTable(rows=0, columns=4)
            widgetDict["boltTable"].setFixedHeight(singleHeight)
            widgetDict["boltTable"].setHorizontalHeaderLabels(
                [
                    "id",
                    "外径",
                    "内径",
                    "材料",
                ]
            )
            widgetDict["boltTable"].rowSetInt([0])
            widgetDict["boltTable"].rowSetFloat([1, 2])
            widgetDict["boltTable"].rowSetSelect(
                [3], options={"3": self.materialOptions}
            )
            widgetDict["boltTable"].addRow()
            boltLayout.addWidget(widgetDict["boltTable"])
            boltGroupBox.setLayout(boltLayout)

            mainLayout.addWidget(pointGroupBox)
            mainLayout.addWidget(boltGroupBox)
            mainGroupBox.setLayout(mainLayout)
            layout.addWidget(mainGroupBox)
        else:
            boltGroupBox = QGroupBox("捆绑连杆")
            boltLayout = QVBoxLayout()
            widgetDict["boltTable"] = OnlyOneRowTable(rows=0, columns=4)
            widgetDict["boltTable"].setFixedHeight(singleHeight)
            widgetDict["boltTable"].setHorizontalHeaderLabels(
                [
                    "id",
                    "外径",
                    "内径",
                    "材料",
                ]
            )
            widgetDict["boltTable"].rowSetInt([0])
            widgetDict["boltTable"].rowSetFloat([1, 2])
            widgetDict["boltTable"].rowSetSelect(
                [3], options={"3": self.materialOptions}
            )
            widgetDict["boltTable"].addRow()
            boltLayout.addWidget(widgetDict["boltTable"])
            boltGroupBox.setLayout(boltLayout)
            layout.addWidget(boltGroupBox)

        self.setStageOptions(
            options=(self.info.get("options0") or {}),
            select=widgetDict["stageType1"],
        )
        self.setStageOptions(
            options=(self.info.get("options1") or {}),
            select=widgetDict["stageType2"],
        )

        self.on_tab_count_changed()

    def libraryChange(self, library):
        if self.isVisible():
            self.materialData = library

    def parseContects(self, contects):
        optionsDict1 = {}
        optionsDict2 = {}

        stages = contects.get("stages") or []
        sections0 = stages[0].get("sections") or {}
        for i, item in enumerate(sections0):
            data = item.get("data") or {}

            if data.get("type") == "shell_bar":
                name = item.get("sectionName")
                optionsDict1["shell_bar"] = (optionsDict1.get("shell_bar") or []) + [
                    name
                ]
            # elif data.get("type") == "point_mass":
            #     ids = self.getIds(type=data.get("type"), data=data)
            #     optionsDict1["point_mass"] = (
            #         (optionsDict1.get("point_mass") or []) + ids + [f"section{i+1}"]
            #     )
            elif data.get("type") == "bar_conm":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict1["bar_conm"] = (optionsDict1.get("bar_conm") or []) + ids
            # elif data.get("type") == "bar_3d":
            #     ids = self.getIds(type=data.get("type"), data=data)
            #     optionsDict1["bar_3d"] = (
            #         (optionsDict1.get("bar_3d") or []) + ids + [f"section{i+1}"]
            #     )

        sections1 = stages[1].get("sections") or {}
        for i, item in enumerate(sections1):
            data = item.get("data") or {}

            if data.get("type") == "shell_bar":
                name = item.get("sectionName")
                optionsDict2["shell_bar"] = (optionsDict2.get("shell_bar") or []) + [
                    name
                ]
            # elif data.get("type") == "point_mass":
            #     ids = self.getIds(type=data.get("type"), data=data)
            #     optionsDict2["point_mass"] = (
            #         (optionsDict2.get("point_mass") or []) + ids + [f"section{i+1}"]
            #     )
            elif data.get("type") == "bar_conm":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict2["bar_conm"] = (optionsDict2.get("bar_conm") or []) + ids
            # elif data.get("type") == "bar_3d":
            #     ids = self.getIds(type=data.get("type"), data=data)
            #     optionsDict2["bar_3d"] = (
            #         (optionsDict2.get("bar_3d") or []) + ids + [f"section{i+1}"]
            #     )

        converted_dict1 = Utils.convertedSortAndFormat(optionsDict1)
        converted_dict2 = Utils.convertedSortAndFormat(optionsDict2)

        dataDict = {}

        dataDict["options0"] = converted_dict1
        dataDict["options1"] = converted_dict2

        return dataDict

    def getIds(self, type, data={}):
        ids = []
        if data:
            if type == "shell_bar":
                ringFrameData = (data.get("grid_set") or [[]]) + (
                    data.get("grid_ring") or [[]]
                )
                for item in ringFrameData:
                    if len(item) > 0:
                        ids.append(item[0])
            elif type == "bar_3d":
                if data.get("grid"):
                    if len(data.get("grid")) > 0 and len(data["grid"][0]) > 0:
                        ids.append(data["grid"][0][0])
                    if len(data.get("grid")) > 1 and len(data["grid"][1]) > 0:
                        ids.append(data["grid"][1][0])
            elif type == "point_mass":
                ids.append(data.get("grid_id"))
            elif type == "bar_conm":
                grid = data.get("grid") or []
                for item in grid:
                    if item and isinstance(item, list) and len(item) > 0:
                        ids.append(item[0])

        ids = [item for item in ids if item is not None]

        return ids

    def getMaterialOption(self):
        options = []
        self.materialData = (
            Utils.read_json(Config.cachePath + "materialLibrary.json") or {}
        )
        if self.materialData:
            for key, _ in self.materialData.items():
                options.append({"title": key, "value": key})
        return options

    def on_okBtn_clicked(self):
        dataList = []

        for i, widgetDict in enumerate(self.tabWidgetList):
            name = self.tabs.tabText(i)
            connectionDict = {"name": name}
            connectionType = widgetDict.get("connectionType").getValue()
            if connectionType == "main":
                for key, widget in widgetDict.items():
                    if key == "id":
                        idValue = widget.getValue()
                        if var_is_empty(idValue):
                            MBox.warning(f"{name}中的id不可为空!")
                            return
                    if (
                        hasattr(widget, "useFlag")
                        and getattr(widget, "useFlag") == False
                    ):
                        continue
                    if isinstance(widget, QTableWidget):
                        temp = widget.getTableData()
                        if key == "pointTable":
                            connectionDict[mainConnectMap[key]] = temp
                        else:
                            if temp and len(temp) >= 1:
                                connectionDict[mainConnectMap[key]] = temp[0]
                    else:
                        if key == "stageType1" or key == "stageType2":
                            continue
                        if (
                            key == "con_id1"
                            and isinstance(widget.getValue(), str)
                            and "section" in widget.getValue()
                        ):
                            connectionDict["section1"] = widget.getValue()
                            continue
                        if (
                            key == "con_id2"
                            and isinstance(widget.getValue(), str)
                            and "section" in widget.getValue()
                        ):
                            connectionDict["section2"] = widget.getValue()
                            continue
                        connectionDict[mainConnectMap[key]] = widget.getValue()
                connectionDict["type"] = (
                    str(typeBundleMap.get(widgetDict["stageType1"].getValue()))
                    + "2"
                    + str(typeBundleMap.get(widgetDict["stageType2"].getValue()))
                )
                connectionDict["part1"] = self.connects.get("connectsTitles")[0].get(
                    "title"
                )
                connectionDict["part2"] = self.connects.get("connectsTitles")[1].get(
                    "title"
                )
                connectionDict = Utils.filter_dict_list(connectionDict)
                connectionDict = Utils.filterDictEmptyProperty(connectionDict)
            else:
                for key, widget in widgetDict.items():
                    if key == "id":
                        idValue = widget.getValue()
                        if var_is_empty(idValue):
                            MBox.warning(f"{name}中的id不可为空!")
                            return
                    if (
                        hasattr(widget, "useFlag")
                        and getattr(widget, "useFlag") == False
                    ):
                        continue
                    if isinstance(widget, QTableWidget):
                        temp = widget.getTableData()
                        if (
                            temp
                            and len(temp) >= 1
                            and key != "scope1Table"
                            and key != "scope2Table"
                        ):
                            connectionDict[rodConnectMap[key]] = temp[0]
                        elif temp:
                            flattened_list = [
                                item for sublist in temp for item in sublist
                            ]

                            connectionDict[rodConnectMap[key]] = flattened_list
                    else:
                        if key == "stageType1" or key == "stageType2":
                            continue
                        if (
                            key == "con_id1"
                            and isinstance(widget.getValue(), str)
                            and "section" in widget.getValue()
                        ):
                            connectionDict["section1"] = widget.getValue()
                            continue
                        if (
                            key == "con_id2"
                            and isinstance(widget.getValue(), str)
                            and "section" in widget.getValue()
                        ):
                            connectionDict["section2"] = widget.getValue()
                            continue
                        connectionDict[rodConnectMap[key]] = widget.getValue()
                connectionDict["type"] = (
                    str(typeBundleMap.get(widgetDict["stageType1"].getValue()))
                    + "2"
                    + str(typeBundleMap.get(widgetDict["stageType2"].getValue()))
                )
                connectionDict["part1"] = self.connects.get("connectsTitles")[0].get(
                    "title"
                )
                connectionDict["part2"] = self.connects.get("connectsTitles")[1].get(
                    "title"
                )
                connectionDict = Utils.filter_dict_list(connectionDict)
                connectionDict = Utils.filterDictEmptyProperty(connectionDict)

            dataList.append(connectionDict)

        self.cacheFile = Config.cachePath + "bundleConnection.json"
        Utils.write_json(self.cacheFile, dataList)
        self.close()
        self.bundleConnection_save_signal.emit(dataList)

    def updateUI(self, data):
        self.isLoading = True
        for i, connection in enumerate(data):
            widgetDict = self.tabWidgetList[i]
            flag = connection.get("connectionType")
            for key, value in connection.items():
                if flag == "main":
                    widget = mainConnectReverseMap.get(key)
                else:
                    widget = rodConnectReverseMap.get(key)
                if widget in widgetDict:
                    if isinstance(widgetDict[widget], QTableWidget):
                        temp = []
                        if widget == "pointTable" and flag == "main":
                            continue
                        if (
                            widget == "scope1Table" or widget == "scope2Table"
                        ) and flag == "rod":
                            if value:
                                temp = [[item] for item in value]
                        else:
                            temp = [value]
                        for rowData in temp:
                            if (
                                widget == "boltTable"
                                or widget == "coordinates1Table"
                                or widget == "coordinates2Table"
                                or (
                                    widget == "scope1Table"
                                    and flag == "main"
                                    or widget == "scope2Table"
                                    and flag == "main"
                                )
                            ):
                                widgetDict[widget].fillRowData(row=0, rowData=rowData)
                            else:
                                widgetDict[widget].addRow(rowData=rowData)
                    elif isinstance(widgetDict[widget], QComboBox):
                        widgetDict[widget].setValue(str(value))
                    else:
                        if widget == "stageType1" or widget == "stageType2":
                            continue
                        widgetDict[widget].setValue(value)

            if flag == "main":
                type = connection.get("type")
                if type and "2" in type:
                    parts = re.split(r"2", type)  # 使用数字作为分隔符分割字符串
                    widgetDict["stageType1"].setValue(
                        typeBundleReverseMap.get(parts[0])
                    )
                    widgetDict["stageType2"].setValue(
                        typeBundleReverseMap.get(parts[-1])
                    )

                if connection.get("con_id1"):
                    widgetDict["con_id1"].setValue(
                        Utils.toInt(connection.get("con_id1"))
                    )
                elif connection.get("section1"):
                    widgetDict["con_id1"].setValue(connection.get("section1"))

                if connection.get("con_id2"):
                    widgetDict["con_id2"].setValue(
                        Utils.toInt(connection.get("con_id2"))
                    )
                elif connection.get("section2"):
                    widgetDict["con_id2"].setValue(connection.get("section2"))

                for row, rowData in enumerate(connection.get("con_grid") or []):
                    widgetDict["pointTable"].fillRowData(row=row, rowData=rowData)
            else:
                type = connection.get("type")
                if type and "2" in type:
                    parts = re.split(r"2", type)  # 使用数字作为分隔符分割字符串
                    widgetDict["stageType1"].setValue(
                        typeBundleReverseMap.get(parts[0])
                    )
                    widgetDict["stageType2"].setValue(
                        typeBundleReverseMap.get(parts[-1])
                    )

                if connection.get("con_id1"):
                    widgetDict["con_id1"].setValue(
                        Utils.toInt(connection.get("con_id1"))
                    )
                elif connection.get("section1"):
                    widgetDict["con_id1"].setValue(connection.get("section1"))

                if connection.get("con_id2"):
                    widgetDict["con_id2"].setValue(
                        Utils.toInt(connection.get("con_id2"))
                    )
                elif connection.get("section2"):
                    widgetDict["con_id2"].setValue(connection.get("section2"))
        self.isLoading = False

    def addTab(self):
        tabNames = [self.tabs.tabText(i) for i in range(self.tabs.count())]
        dlgAddConnection = DlgAddConnection.show(
            parent=self, params={"names": tabNames}
        )
        dlgAddConnection.ok_signal.connect(self.updateTabbar)

    def updateTabbar(self, data={}, type="add", index=0):
        if data:
            if type == "add":
                index = self.tabs.count()
                name = data.get("name")
                connectionType = data.get("type")
                self.createTabPage(name, connectionType, index)
                self.tabs.setCurrentIndex(index)
            else:
                name = data.get("name")
                self.tabs.setTabText(index, name)

    def on_tab_double_clicked(self, index):
        # 获取当前选中的选项卡标题
        name = self.tabs.tabText(index)
        tabNames = [self.tabs.tabText(i) for i in range(self.tabs.count())]
        dlgAddConnection = DlgAddConnection.show(
            parent=self,
            params={"names": tabNames, "name": name, "type": "edit", index: index},
        )
        dlgAddConnection.ok_signal.connect(self.updateTabbar)

    def getStageOptionData(self, select, index):
        options = []
        ls = self.info.get(f"options{index}")
        if select == "点":
            options = ls.get("bar_conm") or []
        elif select == "蒙皮桁条":
            options = ls.get("shell_bar") or []
        return options

    def stageType1Changed(self, *args):
        if self.isLoading:
            widgetDict = self.tabWidgetList[args[1]]
            otherWidgetDict = self.otherWidgetList[args[1]]
        else:
            widgetDict = self.getCurrentWidgetDict()
            otherWidgetDict = self.getCurrentOtherWidgetDict()
        if args[0] == "点":
            self.setStageOptions(
                options=(self.info.get("options1") or {}),
                select=widgetDict["stageType2"],
                previous="点",
            )
            options = self.getStageOptionData("点", 0)
            widgetDict["con_id1"].updateItem(options)
            widgetDict["con_id1"].setVisible(True)
            widgetDict["con_id2"].setVisible(True)
            widgetDict["con_id1"].useFlag = True
            widgetDict["con_id2"].useFlag = True
        elif args[0] == "蒙皮桁条":
            self.setStageOptions(
                options=(self.info.get("options1") or {}),
                select=widgetDict["stageType2"],
                previous="蒙皮桁条",
            )
            options = self.getStageOptionData("蒙皮桁条", 0)
            widgetDict["con_id1"].updateItem(options)
            widgetDict["con_id1"].setVisible(True)
            widgetDict["con_id2"].setVisible(True)
            widgetDict["con_id1"].useFlag = True
            widgetDict["con_id2"].useFlag = True

        self.showTable(widgetDict, otherWidgetDict)

    def stageType2Changed(self, *args):
        if self.isLoading:
            widgetDict = self.tabWidgetList[args[1]]
            otherWidgetDict = self.otherWidgetList[args[1]]
        else:
            widgetDict = self.getCurrentWidgetDict()
            otherWidgetDict = self.getCurrentOtherWidgetDict()
        if args[0] == "点":
            options = self.getStageOptionData("点", 1)
            widgetDict["con_id2"].updateItem(options)
        if args[0] == "蒙皮桁条":
            options = self.getStageOptionData("蒙皮桁条", 1)
            widgetDict["con_id2"].updateItem(options)
        self.showTable(widgetDict, otherWidgetDict)

    def showTable(self, widgetDict, otherWidgetDict):
        if widgetDict["stageType1"].getValue() == "点":
            otherWidgetDict["scope1GroupBox"].setVisible(False)
            widgetDict["scope1Table"].useFlag = False
        elif widgetDict["stageType1"].getValue() == "蒙皮桁条":
            otherWidgetDict["scope1GroupBox"].setVisible(True)
            widgetDict["scope1Table"].useFlag = True
        else:
            otherWidgetDict["scope1GroupBox"].setVisible(False)
            widgetDict["scope1Table"].useFlag = False
        if widgetDict["stageType2"].getValue() == "点":
            otherWidgetDict["scope2GroupBox"].setVisible(False)
            widgetDict["scope2Table"].useFlag = False
        elif widgetDict["stageType2"].getValue() == "蒙皮桁条":
            otherWidgetDict["scope2GroupBox"].setVisible(True)
            widgetDict["scope2Table"].useFlag = True
        else:
            otherWidgetDict["scope2GroupBox"].setVisible(False)
            widgetDict["scope2Table"].useFlag = False

    def on_pointTable_changed(self, row, col):
        if col != 1 and col != 2:
            return
        widgetDict = self.getCurrentWidgetDict()
        table = widgetDict["pointTable"]
        """当单元格内容变化时，同步更新另一列"""
        if row == 0:
            new_value = table.item(row, col).text()
            table.blockSignals(True)  # 避免递归触发信号
            item = table.item(row + 1, col)
            if item:
                item.setText(new_value)
            table.blockSignals(False)
        elif row == 1:
            new_value = table.item(row, col).text()
            table.blockSignals(True)
            item = table.item(row - 1, col)
            if item:
                item.setText(new_value)
            table.blockSignals(False)

    def setStageOptions(self, options, select, previous=""):
        opt = []
        if "bar_conm" in options:
            if previous == "点" or previous == "":
                if {"title": "点", "value": "点"} not in opt:
                    opt.append({"title": "点", "value": "点"})
        if "shell_bar" in options:
            if previous == "蒙皮桁条" or previous == "":
                if {"title": "蒙皮桁条", "value": "蒙皮桁条"} not in opt:
                    opt.append({"title": "蒙皮桁条", "value": "蒙皮桁条"})
        select.updateItem(opt)

    def getCurrentWidgetDict(self):
        tabIndex = self.tabs.currentIndex()
        return self.tabWidgetList[tabIndex]

    def getCurrentOtherWidgetDict(self):
        tabIndex = self.tabs.currentIndex()
        return self.otherWidgetList[tabIndex]


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = BundleConnectionDialog()
#     window.show()
#     sys.exit(app.exec_())
